#!/bin/bash

# init cluster
# args:
#   $1: control plane endpoint host: kube-apiserver.atompi.cc
#   $2: control plane endpoint port: 6443
#   $3: private image registry: hub.atompi.cc/google_containers
#   $4: kubernetes version: 1.21.6 ( with_out "v" )
#   $5: kubernetes podSubnet: 10.244.0.0/16
#   $6: kubernetes serviceSubnet: 10.96.0.0/12

CPE_HOST=$1
CPE_PORT=$2
PRIVATE_HUB=$3
KUBE_VERSION=$4
POD_SUBNET=$5
SERVICE_SUBNET=$6

CPE="$CPE_HOST:$CPE_PORT"
: "${POD_SUBNET:=10.244.0.0/16}"
: "${SERVICE_SUBNET:=10.96.0.0/12}"


# init master
mkdir -p /root/kubesrc && cp -r bin /root/kubesrc && cd /root/kubesrc
cat > kubeadm-config.yaml <<EOF
---
apiVersion: kubeadm.k8s.io/v1beta2
kind: InitConfiguration
localAPIEndpoint:
  advertiseAddress: 0.0.0.0
  bindPort: $CPE_PORT
---
apiVersion: kubeadm.k8s.io/v1beta2
kind: ClusterConfiguration
kubernetesVersion: $KUBE_VERSION
imageRepository: $PRIVATE_HUB
controlPlaneEndpoint: "$CPE"
dns:
  type: CoreDNS
networking:
  dnsDomain: cluster.local
  podSubnet: $POD_SUBNET
  serviceSubnet: $SERVICE_SUBNET
EOF
kubeadm init --config=kubeadm-config.yaml --upload-certs --skip-phases=addon/kube-proxy > kubeadm-init.log

# save cluster info
sleep 60
kubeadm token create --print-join-command > kubeadm-join-worker.sh
certificatekey=$(cat kubeadm-init.log|grep "\-\-certificate\-key"|awk '{print $(NF-1),$(NF)}')
cat > kubeadm-join-master.sh <<EOF
`cat kubeadm-join-worker.sh` --control-plane --certificate-key $certificatekey --apiserver-advertise-address "0.0.0.0" --apiserver-bind-port $CPE_PORT
EOF

mkdir $HOME/.kube
ln -sf /etc/kubernetes/admin.conf $HOME/.kube/config

# install helm
cp bin/helm /usr/local/bin/helm
chmod 755 /usr/local/bin/helm

# install cni (cilium)
cilium_version=1.10.5
helm repo add cilium https://helm.cilium.io/
helm install cilium cilium/cilium --version $cilium_version --namespace kube-system --set kubeProxyReplacement=strict --set k8sServiceHost=$CPE_HOST --set k8sServicePort=$CPE_PORT

sleep 60
kubectl scale deploy -n kube-system cilium-operator --replicas=1
kubectl scale deploy -n kube-system coredns --replicas=1
kubectl taint nodes k8s node-role.kubernetes.io/master-

echo "Congratulations, install finished!!!"
